import json
import re
import random

from django.core.cache import cache
from django.db.models import Q
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView

from user import tasks
from user.models import User
from utils.jwttool import tool
from utils.sendsms import send_message


class LoginPwd(APIView):
    def post(self, request):
        account = request.data.get('account')
        password = request.data.get('password')
        if not account or not password:
            return Response({
                "code":400,
                "msg":"账号或密码不能为空"
            })
        info = User.objects.filter(Q(username=account)|Q(email=account)|Q(phone=account),isdel=False).first()
        if not info:
            return Response({
                "code":400,
                "msg":"账号不存在"
            })
        if info.password != password:
            return Response({
                "code":400,
                "msg":"密码错误"
            })
        token = tool.gettoken(info.id)
        return Response({
            "code":200,
            "msg":"登录成功",
            "data":{
                "token":token,
                "id":info.id
            }
        })
# 获取登陆的验证码
class getcode(APIView):
    def get(self,request):
        # 获取手机号
        phone =request.query_params.get('phone')
        # 验证手机号是否存在，并且符合要求
        if not phone or not re.match("^1[3-9]\d{9}$",phone):
            return Response({
                "msg":"手机号格式不正确",
                "code":400
            })
        # 判断缓存中是否有验证码
        if cache.get(phone):
            return Response({
                "msg":"请勿重复发送验证码",
                "code":400
            })
        # 生成验证码
        code = str(random.randint(1000,9999))
        # 发送短信
        res = tasks.send.delay(phone,code)
        cache.set(phone,code,60*60*24)
        return Response({
            "msg":"验证码发送成功",
            "code":200
        })
        # 非异步发送短信
        # result = send_message(phone,code)
        # res = json.loads(result)
        # if res['statusCode'] == '000000':
        #     # 验证码存入缓存
        #     cache.set(phone,code,60*60*24)
        #     return Response({
        #         "msg":"验证码发送成功",
        #         "code":200
        #     })
        # return Response({
        #     "msg":"验证码发送失败",
        #     "code":400
        # })


class LoginCode(APIView):
    def post(self, request):
        # 获取手机号和验证码
        phone = request.data.get('phone')
        code = request.data.get('code')
        # 验证手机号和验证码是否存在
        if not phone or not code:
            return Response({
                "msg":"手机号或验证码不能为空",
                "code":400
            })
        # 从缓存中获取验证码
        cache_code = cache.get(phone)
        # 判断验证码是否正确
        if str(cache_code) != str(code):
            print(cache_code)
            print(code)
            return Response({
                "msg":"验证码错误",
                "code":400
            })
        # 验证手机号是否再数据库中存在，如果存在 返回用户信息，如果不存在，返回错误信息
        info = User.objects.filter(phone=phone).first()
        if not info:
            info = User.objects.create(phone=phone)

        # 生成token
        token = tool.gettoken(info.id)
        # 返回信息和token
        return Response({
            "msg":"登录成功",
            "code":200,
            "data":{
                "token":token,
                "id":info.id
            }
        })


class register(APIView):
    def post(self, request):
        code = request.data.get('code')
        username = request.data.get('username')
        email = request.data.get('email')
        phone = request.data.get('phone')
        password = request.data.get('password')
        if not code or not username or not email or not phone or not password:
            return Response({
                "msg":"参数不能为空",
                "code":400
            })
        # 验证用户名是否唯一
        info = User.objects.filter(username=username).first()
        if info:
            return Response({
                "msg":"用户名已存在",
                "code":400
            })
        # 验证邮箱是否唯一
        if not re.match("^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$",email):
            return Response({
                "msg":"邮箱格式不正确",
                "code":400
                })
        info = User.objects.filter(email=email).first()
        if info:
            return Response({
                "msg":"邮箱已存在",
                "code":400
            })
        # 验证密码格式和是否唯一
        if not re.match("^[a-zA-Z0-9]{6,20}$",password):
            return Response({
                "msg":"密码格式不正确",
                "code":400
            })
        # 验证手机号是否唯一与格式是否有效
        if not re.match("^1[3-9]\d{9}$",phone):
            return Response({
                "msg":"手机号格式不正确",
                "code":400
            })
        info = User.objects.filter(phone=phone).first()
        if info:
            return Response({
                "msg":"手机号已存在",
                "code":400
            })
        # 验证验证码是否正确
        rediscode = cache.get(phone,"")
        if str(code) != str(rediscode):
            return Response({
                "msg":"验证码错误",
                "code":400
                })
        # 创建用户
        info = User.objects.create(username=username,email=email,phone=phone,password=password)
        # 返回信息和token
        return Response({
            "msg":"注册成功",
            "code":200
            })



# 定义异步任务
import time
# 异步任务装饰器
from celery import shared_task

class Text(APIView):
    def get(self, request):
        # 调用异步任务
        tasks.send_email.delay("张小三")
        return Response({"msg": "测试成功", "code": 200})















